<template>
  <div class="log-main">
    <div class="login-container">
      <div class="title-container">
        <h3 class="title">智慧渔业</h3>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
        label-position="left">
        <div class="input_style">
          <el-form-item prop="account">
            <span class="svg-container">
              <i class="el-icon-office-building" style="font-size: 26px"></i>
            </span>
            <el-input ref="account" v-model="loginForm.account" placeholder="请输入账号名称" name="account" type="text"
              tabindex="1" autocomplete="on" />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <i class="el-icon-unlock" style="font-size: 26px"></i>
            </span>
            <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
              placeholder="请输入登陆密码" name="password" tabindex="2" autocomplete="on" @keyup.enter.native="handleLogin"
              style="color: #ccc" />
            <span class="show-pwd" @click="showPwd">
              <svg-icon style="color: rgba(0, 203, 134, 1)"
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <div class="new-msg">
            <div class="rember-msg">
              <el-checkbox v-model="remberMsg" label="记住密码" />
            </div>
            <!-- <div class="forget-msg" @click.stop="forget">找回密码</div> -->
            <!-- <div class="register-msg" @click.stop="forget">注册用户</div> -->
          </div>
          <el-button :loading="loading" type="primary" class="login-btn" @click.native.prevent="handleLogin">
            登录
          </el-button>
        </div>
        <!-- <div class="reg-user" @click="toreguser()">注册账户</div> -->
      </el-form>
    </div>
    <div class="logo"><img src="~@/assets/login/logo1.png" alt=""></div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { removeloToken, setloToken } from "@/utils/loginAuth";
import { setCookie, getCookie, getpasCookie } from "@/utils/cookie";
import { setToken } from "@/utils/auth";
import axios from "axios";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不得小于六位"));
      } else {
        callback();
      }
    };
    return {
      token: '',
      remberMsg: false,
      loginForm: {
        account: "",
        password: "",
      },
      loginRules: {
        account: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      slider_value: 0,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  mounted() {

  },
  created() {
    if (this.$store.state.permission.addRoutes.length > 0) {
      // 判断是否已经刷新
      location.reload();
    }
    console.log(this.token)
    this.token = this.$route.query.bigsToken
    // 跳转过来时清除sessionStorage
    sessionStorage.clear()
    // 判断sessionStorage 有没有记住密码
    if (localStorage.remberMsg === 'true') {
      this.remberMsg = true
    }
    this.getquery();
  },
  methods: {
    getquery() {
      let accentToken = this.$route.query.accentToken
      let systemFlag = this.$route.query.systemFlag ? this.$route.query.systemFlag : 'sociallize'
      if (accentToken) {
        sessionStorage.clear()
        localStorage.clear()
        axios.post(this.$baseurl.webServiceUrl + 'userManagement/user/authenticationByAccessToken',
          { "accessToken": accentToken.replaceAll(' ', '+'), "applicationName": systemFlag },
        ).then(res => {
          if (res.data.success && res.data.data) {
            sessionStorage.setItem("token", res.data.data)
            setToken("token", res.data.data);
            this.$router.push({ path: "/choose-system" });
          } else {
            let msgInfo = ''
            switch (res.data.message) {
              case "错误的凭证. error: 1":
                msgInfo = '系统名错误'
                break;
              case "错误的凭证. error: 2":
                msgInfo = '使用了错误的key进行解密'
                break;
              case "错误的凭证. error: 3":
                msgInfo = '凭证格式错误'
                break;
              case "错误的凭证. error: 4":
                msgInfo = '拼接的系统名和传入参数的系统名不一致'
                break;
              case "错误的凭证. error: 5":
                msgInfo = '凭证过期'
                break;
              case "错误的凭证. error: 6":
                msgInfo = '对应电话号码未绑定用户'
                break;
              default:
                msgInfo = '未配置手机号请联系管理员给您配置手机号吧！'
            }
            this.$message.error(msgInfo)
          }
        });
        return
      }
      if (this.token) {
        setToken("token", this.token);
        this.$router.push({ path: "/choose-system" });
      } else {
        let tr = this.$route.query;
        if (tr.account) {
          this.loginForm.account = decodeURIComponent(tr.account);
          this.loginForm.password = tr.password;
          setTimeout(() => {
            this.handleLogin();
          }, 200);
        } else if (tr.token) {
          // 避免明文 url 链接
          let token = decodeURIComponent(window.location.href.split('?')[1].split('=')[1]).replace(/ /g, "+")
          let obj = getpasCookie(token)
          this.loginForm.account = obj.account;
          this.loginForm.password = obj.password;
          setTimeout(() => {
            this.handleLogin();
          }, 200)
        } else if (this.remberMsg === true) {
          // 从cookie 获取
          let loginForm = getCookie()
          this.$set(this.loginForm, 'account', loginForm.account)
          this.$set(this.loginForm, 'password', loginForm.password)
        }
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store.dispatch("user/login", this.loginForm).then(() => {
            this.loading = false;
            // 存储加密账号密码到cookie
            if (this.remberMsg) {
              setCookie(this.loginForm.account, this.loginForm.password, 15)
              setloToken('remberMsg', this.remberMsg)
            } else {
              removeloToken('remberMsg')
            }
            this.$router.push({ path: "/choose-system", params: { homeBaseId: this.$route.query.homeBaseId } });
          }).catch((err) => {
            this.$message.warning(err || "用户账号/密码错误(或已被加入黑名单),请确认后重试或联系管理员");
            this.loading = false;
          });
        } else {
          console.log("表单提交错误!!");
          return false;
        }
      });
    },
    // 忘记密码
    // forget() {
    //   this.$router.push({ path: "/find-password" });
    // },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #283443;
$light_gray: #9B9B9B;
$cursor: #9B9B9B;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* 登录主体样式 */
.login-container {
  .el-input {
    display: inline-block;
    height: 40px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      --webkit-appearance: none;
      border-radius: 0px;
      color: $light_gray;
      // box-sizing: border-box;
      margin-left: 10px;
      width: 95%;
      height: 40px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 100px #fff inset !important;
        -webkit-text-fill-color: #ccc !important;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #9B9B9B;
$light_gray: #9B9B9B;

.log-main {
  width: 100%;
  height: 100%;
  background-size: 100% 100% !important;
  background-attachment: fixed !important;
  background: url("~@/assets/login/back.jpg") center center no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  background-image: url("~@/assets/login/login-top.png");
  background-repeat: no-repeat;
  background-position: top center;
  position: relative;
  height: 375px;
  width: 26%;
  display: flex;
  background-color: #fff;
  box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.51);
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .login-form {
    position: relative;
    width: 65%;
    top: -20px;
    z-index: 99;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    margin-bottom: 20px;

    .title {
      font-size: 33px;
      font-weight: bold;
      color: #2A94FC;
      letter-spacing: 8px;
      text-align: center;
    }
  }

  .input_style {

    // box-sizing: border-box;
    .svg-container {
      color: #037ffb;
    }

    ::v-deep .el-form-item__content {
      border: 1px solid rgba(217, 217, 217, 1);
      border-radius: 2px;
      background-color: #fff;
    }

    // 记住密码与忘记密码
    .new-msg {
      display: flex;
      width: 100%;
      color: #0080ff;
      font-size: 14px;
      justify-content: space-between;

      .rember-msg {
        width: 80px;
        height: 22px;
        color: #0080ff;
        font-size: 14px;
        line-height: 22px;

        .el-checkbox {
          color: #0080ff;
          font-size: 14px;
        }
      }

      .forget-msg {
        width: 56px;
        height: 22px;
        // margin-left: 20px;
        color: #0080ff;
        font-size: 14px;
        line-height: 22px;
        cursor: pointer;
      }
    }

    //登陆按钮
    .login-btn {
      width: 100%;
      background-color: #0080ff;
      margin-top: 20px;
      height: 40px;
      font-size: 20px;
      letter-spacing: 4px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

.logo {
  width: 400px;
  position: absolute;
  bottom: 20px;

  img {
    width: 400px;
  }
}
</style>
